from datetime import datetime
from sys import stderr

from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_app
from django.utils.translation import ugettext

from django.contrib.auth.models import User

from taskberry.apps.tasks.models import Task, TaskHistory, workflow
from taskberry.apps.tasks.widgets import ReadOnlyWidget

from pinax.apps.tagging_utils.widgets import TagAutoCompleteInput
from tagging.forms import TagField

class JQueryUIDatepickerWidget(forms.DateInput):
    def __init__(self, **kwargs):
        super(forms.DateInput, self).__init__(attrs={"size":10, "class":
                                                     "dateinput",
                                                     "autocomplete":
                                                     "off"}, **kwargs)

    class Media:
        css = {"all":("/static/css/cupertino/jquery-ui-1.8.7.custom.css",)}
        js = ("/static/js/jquery-ui-1.8.7.custom.min.js",
              "/static/pinax/js/jquery-1.3.2.min.js",)


class TaskForm(forms.ModelForm):
    """
    Form for creating tasks
    """
    
    tags = TagField(
        required = False,
        widget = TagAutoCompleteInput(app_label="tasks", model="task")
    )
    
    def __init__(self, user, group, *args, **kwargs):
        self.user = user
        self.group = group
        
        super(TaskForm, self).__init__(*args, **kwargs)
        
        self.fields["summary"].widget.attrs["size"] = 65
        self.fields["planned_date"].widget = JQueryUIDatepickerWidget()
    
    class Meta:
        model = Task
        fields = ["summary", "detail", "tags", "markup",
                  "planned_date", "recur" ]

    def clean(self):
        self.check_group_membership()
        return self.cleaned_data
    
    def check_group_membership(self):
        group = self.group
        if group and not self.group.user_is_member(self.user):
            raise forms.ValidationError("You must be a member to create tasks")


class EditTaskForm(forms.ModelForm):
    """
    Form for editing tasks
    """
    
    tags = TagField(
        required = False,
        widget = TagAutoCompleteInput(app_label="tasks", model="task")
    )
    
    def __init__(self, user, group, *args, **kwargs):
        self.user = user
        self.group = group
        
        super(EditTaskForm, self).__init__(*args, **kwargs)
        
        self.fields["planned_date"].widget = JQueryUIDatepickerWidget()
        self.fields["summary"].widget.attrs["size"] = 65
        self.fields.keyOrder = [
            "summary",
            "detail",
            "tags",
            "planned_date",
            "recur",
        ]
        
    class Meta(TaskForm.Meta):
        model = Task
        fields = [
            "summary",
            "detail",
            "tags",
            "planned_date",
            "recur",
        ]
    
    def clean_resolution(self):
        if self.cleaned_data["state"] == u"2":
            if not self.cleaned_data["resolution"]:
                raise forms.ValidationError(
                    ugettext("You must provide a resolution to mark this task as resolved")
                )
        return self.cleaned_data["resolution"]
